package com.example.ivideo_2211a.home

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.ivideo_2211a.R
import com.example.ivideo_2211a.databinding.ItemVideoBinding

/**
 * 视频列表适配器
 */
class VideoAdapter(private val onVideoClick: (HomeData) -> Unit = {}) : ListAdapter<HomeData, VideoAdapter.VideoViewHolder>(VideoDiffCallback()) {
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
        val binding: ItemVideoBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.item_video,
            parent,
            false
        )
        return VideoViewHolder(binding, onVideoClick)
    }
    
    override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {
        holder.bind(getItem(position))
    }
    
    class VideoViewHolder(
        private val binding: ItemVideoBinding,
        private val onVideoClick: (HomeData) -> Unit
    ) : RecyclerView.ViewHolder(binding.root) {
        
        fun bind(video: HomeData) {
            binding.video = video
            binding.executePendingBindings()// 执行挂起的绑定
            
            // 设置点击事件
            binding.root.setOnClickListener {
                onVideoClick(video)
            }
            
            // 这里可以使用Glide或其他图片加载库加载图片
            Glide.with(binding.root.context)
                .load(video.videomainimag)
                .into(binding.videoThumbnail)

            Glide.with(binding.root.context)
                .load(video.avatar_url)
                .into(binding.userAvatar)
        }
    }
    
    class VideoDiffCallback : DiffUtil.ItemCallback<HomeData>() {
        override fun areItemsTheSame(oldItem: HomeData, newItem: HomeData): Boolean {
            return oldItem.id == newItem.id
        }
        override fun areContentsTheSame(oldItem: HomeData, newItem: HomeData): Boolean {
            return oldItem == newItem
        }
    }
}